package com.buba.appointment.controller;


import com.buba.appointment.data.vo.NucleicAcidAppointmentVo;
import com.buba.appointment.data.vo.NucleicAcidConfirmAppointmentVo;
import com.buba.appointment.service.NucleicAcidService;
import com.buba.appointment.vo.NucleicAcidVo;
import com.buba.pojo.appointment.NucleicAcid;
import com.buba.pojo.record.Record;
import com.buba.server.record.ServerRecordService;
import com.buba.server.user.PatientCardService;
import com.buba.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import static java.lang.Integer.parseInt;

/**
 * <p>
 * 核酸预约表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-06-09
 */
@Slf4j
@RestController
@RequestMapping("/appointment/nucleic-acid")
public class NucleicAcidController {
    @Autowired
    //@Qualifier("hisDataRedisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private NucleicAcidService naService;
    @Resource(name = "hisDataRedisTemplate")
    private RedisTemplate redisTemplate2;
    @Autowired
    private PatientCardService pcService;
    @Autowired
    private ServerRecordService srService;

    //查询核算记录详情
    @GetMapping("/nucleicDetails/{id}")
    public R nucleicDetails(@PathVariable Integer id){
        NucleicAcidVo nucleicAcidVo = naService.nucleicDetails(id);
        return R.ok().data("nucleic" , nucleicAcidVo);
    }

    //根据就诊人id查询核酸检测结果
    @GetMapping("/nucleicResult/{id}")
    public R nucleicResult(@PathVariable Integer id){
        List<NucleicAcidVo> nucleicAcidVos = naService.nucleicResult(id);
        return R.ok().data("nucleic" , nucleicAcidVos);
    }

    //根据就诊人查询核酸记录
    @GetMapping("/nucleicById/{id}")
    public R nucleicById(@PathVariable Integer id){
        NucleicAcidVo nucleicAcidVo = naService.nucleicById(id);
        return R.ok().data("nucleic" , nucleicAcidVo);
    }

    //根据就诊人查询核酸预约记录
    @GetMapping("/nucleiRecord/{id}/{begin}/{end}")
    public R nucleiRecord(@PathVariable Integer id , @PathVariable String begin , @PathVariable String end){
        log.info("begin::"+begin);
        log.info("end::"+end);
        List<NucleicAcidVo> nucleicAcidVos = naService.nucleiRecord(id , begin , end);
        return R.ok().data("nucleicAcid" , nucleicAcidVos);
    }

    /**
     * todo 核酸预约,先redis中扣除一个号源
     * @param vo
     * @return com.buba.utils.R
     * @author xhh
     * @data 2022/6/15 11:26
     */
    @Transactional
    @RequestMapping(value = "/nucleicAcidAppointment",method = RequestMethod.POST)
    public R nucleicAcidAppointment(@RequestBody NucleicAcidAppointmentVo vo) {
        log.info("================= /appointment/nucleic-acid/nucleicAcidAppointment ======================{}",vo);

        LocalTime time = vo.getTime();
        Integer timeI = time.getHour() * 100 + time.getMinute();
        LocalDate date = vo.getDate();
        Integer numberSource = 0;
        Integer patientId = vo.getPatientId();
        redisTemplate.watch(date.toString());
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        if(zSetOperations==null){
            return R.error();
        }
        System.err.println(zSetOperations.rangeByScore(date.toString(),0,2400));
        Set<LinkedHashMap> set = zSetOperations.rangeByScore(date.toString(), timeI, timeI);
        System.err.println(set);
        for (LinkedHashMap linkedHashMap : set) {
            for (Object o : linkedHashMap.keySet()) {
                LocalTime t = LocalTime.parse(o.toString(), DateTimeFormatter.ofPattern("HH:mm"));
                if (t.compareTo(time) != 0) {
                    return R.error();
                }
                numberSource = parseInt(linkedHashMap.get(o).toString());
                if (numberSource <= 0) {
                    R r = R.error();
                    r.setMessage("号源没了");
                    return r;
                } else {
                    /*从redis中减去一个号源的操作*/
                    LinkedHashMap map = new LinkedHashMap();
                    map.put(o, numberSource - 1);
                    zSetOperations.remove(date.toString(), linkedHashMap);
                    zSetOperations.add(date.toString(), map, timeI);
                    redisTemplate2.opsForValue().set(patientId.toString(),date.toString()+" "+time.toString());
                    /*向mysql中添加用户记录*/
                    //NucleicAcid nucleicAcid = new NucleicAcid();
                    //nucleicAcid.setPatientId(userId);
                    //SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    //nucleicAcid.setVisitTime(dateFormat.parse(date.toString() +" " +time.toString()));
                    //
                    //nucleicAcid.setCampusId(vo.getCampusId());
                    //naService.save(nucleicAcid);
                    //redisTemplate.exec();
                    return R.ok();
                }
            }
        }
        return R.error();
    }
    /**
     * todo 核酸确认预约回显
     * @param hospitalNumber
     * @return com.buba.utils.R
     * @author xhh
     * @data 2022/6/16 15:20
     */
    @Transactional
    @RequestMapping(value = "/nucleicAcidAppointmentConfirmEcho",method = RequestMethod.POST)
    public R nucleicAcidAppointmentConfirmEcho(@RequestParam("userId")Integer userId,@RequestParam("hospitalNumber")String hospitalNumber) {
        //Integer integer= parseInt(redisTemplate2.opsForValue().get(patientId.toString()).toString());

        R r = pcService.getBlaceByUserId(userId,hospitalNumber);
        return R.ok().data("rechargeExplain","检测费").data("rechargeExplainId",3)
                .data("department","保健室").data("departmentId",42).data("balance",r.getData().get("balance"))
                .data("projectName","核酸检测").data("cost",150);
    }
    /**
     * todo 核酸确认预约 要先扣钱 充值记录表里加数据 redis中确认支付 核酸表增加记录
     * @param vo
     * @return com.buba.utils.R
     * @author xhh
     * @data 2022/6/16 15:20
     */
    @Transactional
    @RequestMapping(value = "/nucleicAcidAppointmentConfirm",method = RequestMethod.POST)
    public R nucleicAcidAppointmentConfirm(@RequestBody NucleicAcidConfirmAppointmentVo vo) throws ParseException {
        //要先卡号扣钱
        System.out.println(vo);
        R r = pcService.deductMoney(vo.getMoney(), vo.getHospitalNumber());
        if(!r.getSuccess()){
            return R.error();
        }
        //充值记录表里加数据
        R r3 = pcService.getIdByhospitalNumber(vo.getHospitalNumber());
        if(!r3.getSuccess()){
            return R.error();
        }
        Record record=new Record();
        record.setMoney(new BigDecimal(0).subtract(vo.getMoney()));
        record.setPatientId(vo.getPatientId());
        record.setPatientcardDi(Integer.parseInt(r3.getData().get("id").toString()));
        record.setRechargeExplain("6");
        R r1 = srService.payRecord(record);
        if(!r1.getSuccess()){
            return R.error();
        }

        //核酸表增加记录
        NucleicAcid nucleicAcid = new NucleicAcid();
        nucleicAcid.setPatientId(vo.getPatientId());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Object o = redisTemplate2.opsForValue().get(vo.getPatientId().toString());
        nucleicAcid.setVisitTime(dateFormat.parse(o.toString()));
        nucleicAcid.setCampusId(vo.getCampusId());
        nucleicAcid.setDepartmentId(42);
        nucleicAcid.setUpdateTime(new Date());
        nucleicAcid.setDoctorId(1);
        nucleicAcid.setCost(new BigDecimal(150));
        naService.save(nucleicAcid);

        //redis中确认支付
        redisTemplate2.opsForValue().set(vo.getPatientId().toString(),"已支付");

        return R.ok();

    }

    @Autowired
    private NucleicAcidService nucleicAcidService;
    //修改核酸状态
    @PostMapping("/updatehsState")
    public R updatehsState(@RequestBody NucleicAcid nucleicAcid){
        nucleicAcid.setState("已检测");
        nucleicAcid.setUpdateTime(new Date());
        boolean update=nucleicAcidService.updateById(nucleicAcid);
        //int update=nucleicAcidService.updatehsState(nucleicAcid);
        //修改核酸预约状态
        if(update == true){
            return R.ok().data("ok","修改成功");
        }else {
            return R.ok().data("error","修改失败");
        }
    }
}

